﻿///////////////////////////////////////////////////////////////////////////////
//
//  This file is part of MathLib.NET.
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//  
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//  
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library;  If not, see 
//  <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////////////

using System.Diagnostics;

namespace MathLib
{
    /// <summary>
    /// Miscellaneous utility functions.
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// Generates output in the debug window.
        /// </summary>
        /// <param name="format">String format</param>
        /// <param name="args">Arguments</param>
        public static void trace(string format, params object[] args)
        {
            Debug.WriteLine(format, args);
        }

        /// <summary>
        /// Convert indices to a flat index.
        /// </summary>
        /// <param name="sizes">Array of dimensions sizes</param>
        /// <param name="indices">Array of indices</param>
        /// <returns>Flat index</returns>
        public static int indicesToFlat(int[] sizes, int[] indices)
        {
            int N = indices.Length;
            int flat = indices[N - 1];
            for (int d = 1; d < N; d++)
            {
                int nd = N - d - 1;
                flat *= sizes[nd];
                flat += indices[nd];
            }
            return flat;
        }

        /// <summary>
        /// Increment indices by given steps
        /// </summary>
        /// <param name="starts">Array of dimension start indices</param>
        /// <param name="steps">Array of steps to increment by</param>
        /// <param name="stops">Array of dimension stop indices</param>
        /// <param name="indices">Array of indicies</param>
        public static void indicesInc(int[] starts, int[] steps, int[] stops, ref int[] indices)
        {
            int N = indices.Length;
            for (int d = 0; d < N; d++)
            {
                indices[d] += steps[d];
                if (indices[d] <= stops[d]) break;

                indices[d] = starts[d];
            }
        }
    }
}
